﻿using System.Data;
using System.Data.Common;
using IMClient.Model;
using IMClient.Model.Message;
using IMClient.Model.UI;

namespace IMClient.Cache.Repositories
{
    public class ChatRecordRepository
    {
        private readonly DbContext _dbContext;

        public ChatRecordRepository()
        {
            _dbContext = DbContext.Instance;
        }

        // 保存聊天记录（支持好友和群聊）
        public async Task SaveChatRecordAsync(BaseMessage message, ChatParticipantViewModel participant, string userId)
        {
            if (message.ReceiverId == User.UserId)
            {
                return;
            }

            using var connection = _dbContext.GetConnection();
            await EnsureConnectionOpenAsync(connection); 
            using var transaction = await connection.BeginTransactionAsync();

            string participantId = participant is FriendViewModel ? participant.Id : ((GroupViewModel)participant).Id;
            string participantType = participant is FriendViewModel ? "friend" : "group";
            string participantName = participant.Name;
            string participantAvatar = participant.Avatar;

            // 检查记录是否存在
            var checkCommand = connection.CreateCommand();
            checkCommand.CommandText = @"
                SELECT COUNT(1) FROM chat_records WHERE friend_id = $participantId AND user_id = $userId";
            checkCommand.Parameters.AddWithValue("$participantId", participantId);
            checkCommand.Parameters.AddWithValue("$userId", userId);

            var exists = Convert.ToInt32(await checkCommand.ExecuteScalarAsync()) > 0;

            if (exists)
            {
                // 更新记录
                var updateCommand = connection.CreateCommand();
                updateCommand.CommandText = @"
                    UPDATE chat_records
                    SET last_message = $lastMessage, last_message_time = $lastMessageTime, type = $type
                    WHERE friend_id = $participantId AND user_id = $userId";
                updateCommand.Parameters.AddWithValue("$participantId", participantId);
                updateCommand.Parameters.AddWithValue("$lastMessage", message.Content);
                updateCommand.Parameters.AddWithValue("$lastMessageTime",
                    message.Timestamp.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"));
                updateCommand.Parameters.AddWithValue("$type", participantType);
                updateCommand.Parameters.AddWithValue("$userId", userId);

                await updateCommand.ExecuteNonQueryAsync();
            }
            else
            {
                // 插入记录
                var insertCommand = connection.CreateCommand();
                insertCommand.CommandText = @"
                    INSERT INTO chat_records (friend_id, friend_name, friend_avatar, last_message, last_message_time, user_id, type)
                    VALUES ($participantId, $participantName, $participantAvatar, $lastMessage, $lastMessageTime, $userId, $type)";
                insertCommand.Parameters.AddWithValue("$participantId", participantId);
                insertCommand.Parameters.AddWithValue("$participantName", participantName);
                insertCommand.Parameters.AddWithValue("$participantAvatar", participantAvatar ?? "");
                insertCommand.Parameters.AddWithValue("$lastMessage", message.Content);
                insertCommand.Parameters.AddWithValue("$lastMessageTime",
                    message.Timestamp.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"));
                insertCommand.Parameters.AddWithValue("$userId", userId);
                insertCommand.Parameters.AddWithValue("$type", participantType);

                await insertCommand.ExecuteNonQueryAsync();
            }

            await transaction.CommitAsync();
        }

        // 根据当前用户 ID 获取聊天记录
        public async Task<List<ChatParticipantViewModel>> GetChatRecordsByUserIdAsync(string userId)
        {
            var chatRecords = new List<ChatParticipantViewModel>();

            using var connection = _dbContext.GetConnection();
            await EnsureConnectionOpenAsync(connection); 

            using var command = connection.CreateCommand();
            command.CommandText = @"
                SELECT friend_id, friend_name, friend_avatar, last_message, last_message_time, type
                FROM chat_records
                WHERE user_id = $userId
                ORDER BY datetime(last_message_time) DESC";
            command.Parameters.AddWithValue("$userId", userId);

            using var reader = await command.ExecuteReaderAsync();
            while (await reader.ReadAsync())
            {
                var participantId = reader.GetString(0);
                var participantName = reader.GetString(1);
                var participantAvatar = reader.GetString(2);
                var lastMessage = reader.GetString(3);
                var lastMessageTime = reader.GetString(4);
                var type = reader.GetString(5);

                if (type == "group")
                {
                    chatRecords.Add(new GroupViewModel
                    {
                        Id = participantId,
                        Name = participantName,
                        Avatar = participantAvatar,
                        LastMessage = lastMessage,
                        LastMessageTime = lastMessageTime
                    });
                }
                else
                {
                    chatRecords.Add(new FriendViewModel
                    {
                        Id = participantId,
                        Name = participantName,
                        Avatar = participantAvatar,
                        LastMessage = lastMessage,
                        LastMessageTime = lastMessageTime
                    });
                }
            }

            return chatRecords;
        }
        public async Task UpdateGroupAvatarAsync(string groupId, string newAvatar, string userId)
        {
            using var connection = _dbContext.GetConnection();
            await EnsureConnectionOpenAsync(connection); 
            var command = connection.CreateCommand();
            command.CommandText = @"
            UPDATE chat_records
            SET friend_avatar = $newAvatar
            WHERE friend_id = $groupId AND user_id = $userId AND type = 'group'";
            command.Parameters.AddWithValue("$newAvatar", newAvatar);
            command.Parameters.AddWithValue("$groupId", groupId);
            command.Parameters.AddWithValue("$userId", userId);

            await command.ExecuteNonQueryAsync();
        }


        public async Task UpdateGroupNameAsync(string groupId, string newName, string userId)
        {
            using var connection = _dbContext.GetConnection();
            await EnsureConnectionOpenAsync(connection);

            var command = connection.CreateCommand();
            command.CommandText = @"
            UPDATE chat_records
            SET friend_name = $newName
            WHERE friend_id = $groupId AND user_id = $userId AND type = 'group'";
            command.Parameters.AddWithValue("$newName", newName);
            command.Parameters.AddWithValue("$groupId", groupId);
            command.Parameters.AddWithValue("$userId", userId);

            await command.ExecuteNonQueryAsync();
        }
        // 确保数据库连接已打开
        private static async Task EnsureConnectionOpenAsync(DbConnection connection)
        {
            if (connection.State != ConnectionState.Open)
            {
                await connection.OpenAsync();
            }
        }
    }
}
